<template>
  <div class="mb-4">
    <el-button type="success" class="edit" @click="addClue">录入线索</el-button>
    <el-button type="danger" class="edit" @click="batchDelClue">批量删除</el-button>
    <el-button type="primary" class="edit" @click="importExcel">导入线索Excel</el-button>
  </div>
  <el-dialog
      v-model="importDialog"
      title="导入Excel文件"
      width="500"
      align-center
  >
    <!--手动发送请求 http-request ajax-->
    <el-upload
        ref="uploadRef"
        class="upload-demo"
        method="post"
        :auto-upload="false"
        :http-request=uploadRequest
        accept='.xlsx, .xls'
    >
      <template #trigger>
        <el-button type="primary">选择文件</el-button>
      </template>
      <div>注意：</div>
      <ul>
        <li>请上传.xls或者xlsx的文件</li>
      </ul>
    </el-upload>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="importDialog = false">取消</el-button>
        <el-button class="ml-3" type="success" @click="submitUpload">
          点击上传
        </el-button>
      </div>
    </template>
  </el-dialog>

<!--弹窗  -->
  <el-dialog v-model="dialogFormVisible" :title="clueQuery.id > 0 ? '编辑' : '录入线索'" width="500" style="text-align: center">
    <el-form :model="clueQuery" :rules="dialogFormRules" ref="dialogRef">

      <el-form-item label="负责人" prop="ownerId">
        <el-select
            v-model="clueQuery.ownerId"
            clearable
            placeholder="请选择负责人"
            style="width: 240px"
        >
          <el-option
              v-for="item in clueUserSelect"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="所属活动" prop="activityId">
        <el-select
            v-model="clueQuery.activityId"
            clearable
            placeholder="请选择所属活动"
            style="width: 240px"
        >
          <el-option
              v-for="item in activitySelect"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          />
        </el-select>

      </el-form-item>

      <el-form-item label="姓名" prop="fullName">
        <el-input v-model="clueQuery.fullName" />
      </el-form-item>

      <el-form-item label="称呼" prop="appellation">
        <el-select
            v-model="clueQuery.appellation"
            clearable
            placeholder="请选择称呼"
            style="width: 240px"
        >
          <el-option
              v-for="item in  appellationSelect"
              :key="item.id"
              :label="item.typeValue"
              :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="手机" prop="phone">
        <el-input v-model="clueQuery.phone" />
      </el-form-item>

      <el-form-item label="微信" prop="weixin">
        <el-input v-model="clueQuery.weixin" />
      </el-form-item>

      <el-form-item label="qq" prop="qq">
        <el-input v-model="clueQuery.qq" />
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input v-model="clueQuery.email" />
      </el-form-item>

      <el-form-item label="年龄" prop="age">
        <el-input v-model="clueQuery.age" />
      </el-form-item>

      <el-form-item label="职业" prop="job">
        <el-input v-model="clueQuery.job" />
      </el-form-item>

      <el-form-item label="年收入" prop="yearIncome" >
        <el-input v-model="clueQuery.yearIncome" placeholder="万元"/>
      </el-form-item>

      <el-form-item label="地址" prop="address">
        <el-input v-model="clueQuery.address" />
      </el-form-item>

      <el-form-item label="是否需要贷款" prop="needLoan">
        <el-select
            v-model="clueQuery.needLoan"
            clearable
            placeholder="请选择需要贷款"
            style="width: 240px"
        >
          <el-option
              v-for="item in needLoadSelect"
              :key="item.id"
              :label="item.typeValue"
              :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="意向状态" prop="intentionState">
        <el-select
            v-model="clueQuery.intentionState"
            clearable
            placeholder="请选择意向状态"
            style="width: 240px"
        >
          <el-option
              v-for="item in intentionStateSelect"
              :key="item.id"
              :label="item.typeValue"
              :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item v-show="clueQuery.intentionState == 46" label="意向产品" prop="intentionProduct">
        <el-select
            v-model="clueQuery.intentionProduct"
            clearable
            placeholder="请选择意向产品"
            style="width: 240px"
        >
          <el-option
              v-for="item in productSelect"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="线索状态" prop="state">
        <el-select
            v-model="clueQuery.state"
            clearable
            placeholder="请选择线索状态"
            style="width: 240px"
        >
          <el-option
              v-for="item in clueStateSelect"
              :key="item.id"
              :label="item.typeValue"
              :value="item.id"
          />
        </el-select>
      </el-form-item>


      <el-form-item label="线索来源" prop="source">
        <el-select
            v-model="clueQuery.source"
            clearable
            placeholder="请选择线索状态"
            style="width: 240px"
        >
          <el-option
              v-for="item in sourceSelect"
              :key="item.id"
              :label="item.typeValue"
              :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="备注" prop="description">
        <el-input type="textarea" v-model="clueQuery.description" />
      </el-form-item>


      <el-form-item label="下次联系时间" prop="nextContactTime">
        <el-date-picker
            v-model="clueQuery.nextContactTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择活动结束时间"
        />
      </el-form-item>


    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitClue">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>



  <el-table :data="clueList"
            style="width: 100%"
            @selection-change="selectionChange"
  >
    <el-table-column type="selection" width="30" />
    <el-table-column type="index" label="序号" width="70"/>
    <el-table-column property="ownerName" label="负责人" />
    <el-table-column property="activityName" label="所属活动" width="150"/>
    <el-table-column property="fullName" label="姓名" />
    <el-table-column property="appellationName" label="称呼"/>
    <el-table-column property="phone" label="手机" show-overflow-tooltip width="120"/>
    <el-table-column property="weixin" label="微信" show-overflow-tooltip width="120"/>
    <el-table-column property="qq" label="qq" show-overflow-tooltip width="120"/>
    <el-table-column property="email" label="邮箱" show-overflow-tooltip width="120"/>
    <el-table-column property="age" label="年龄" show-overflow-tooltip width="70"/>
    <el-table-column property="job" label="职业" show-overflow-tooltip />
    <el-table-column property="yearIncome" label="年收入" width="100" show-overflow-tooltip/>
    <el-table-column property="address" label="地址" width="150" show-overflow-tooltip/>
    <el-table-column property="needLoanInfo" label="是否需要贷款" width="150" show-overflow-tooltip/>
    <el-table-column property="istateInfo" label="意向状态" show-overflow-tooltip/>
    <el-table-column property="iproductInfo" label="意向产品" width="120" show-overflow-tooltip/>
    <el-table-column property="stateInfo" label="线索状态" width="120" show-overflow-tooltip/>
    <el-table-column property="sourceInfo" label="线索来源" width="160" show-overflow-tooltip/>
    <el-table-column property="nextContactTime" label="下次联系时间" width="200" show-overflow-tooltip/>
    <el-table-column label="操作" width="250">
<!--使用插槽获取用户信息-->
      <template #default="scope">
        <el-button type="primary" @click="details(scope.row.id)">详情</el-button>
        <el-button type="success" @click="editClue(scope.row.id)">编辑</el-button>
        <el-button type="danger" @click="delClue(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <p></p>
  <p></p>
  <p></p>
    <el-pagination
        class="page"
        background
        :page-size=pageSize
        layout="prev, pager, next"
        @current-change="page"
        @prev-click="page"
        @next-click="page"
        :total=total />
</template>

<script>
import {doDelete, doGet, doPost, doPut} from "@/http/httpRequest";
import {confirmMessageTip, messageTip} from "@/util/utils";

export default {
  name:"ClueControlView",
  data(){
    return{
      clueList:[{}],
      pageSize:0,
      total:0,
      dialogFormVisible : false,
      clueQuery : {},
      clueIdArray:[],
      clueUserSelect:[],
      activitySelect:[],
      appellationSelect:[],
      needLoadSelect:[],
      intentionStateSelect:[],
      intentionProductSelect:[],
      clueStateSelect:[],
      sourceSelect:[],
      productSelect:[],
      importDialog:false,
      flag:1,
      dialogFormRules : {
        fullName: [
            {required:true, message: "请输入", trigger:'blur'}
          ],
        phone: [
          {required:true, pattern:/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/, message: "请输入正确的手机号", trigger:'blur'}
        ],
        email: [
          {required:true, pattern:/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/ , message: "请输入正确的邮箱", trigger:'blur'}
        ],
      },
    }
  },
  //父页面的函数使用
  inject:['reload'],
  methods:{
    /**
     * 导入Excel组件
     */
    importExcel() {
      this.importDialog = true;
    },
    selectionChange(dataArray) {
       // alert(JSON.stringify(data.get(id)))
      this.clueIdArray = [],
      dataArray.forEach(data =>{
        this.clueIdArray.push(data.id)
      })
    },
    /**
     * 上传文件 this.$refs.upload.submit()自动调用httpRequest方法
     * @param param 回调参数
     */
    uploadRequest(param) {
      console.log(param)
      //console.log(this.flag ++ )

      let fileObj = param.file;
      let formData = new FormData;
      formData.append("file", fileObj)
      doPost("api/importExcel", formData).then(res =>{
        if (res.data.code === 200) {
          messageTip("导入成功", "success")
          this.reload();
          //
        }
      })
    },
    /**
     * 回调uploadRequest
     */
    submitUpload() {
      this.$refs.uploadRef.submit()
    },
    getClueInfo(current){
      doGet("/api/getClues",{
        current:current
      }).then(res =>{
        if (res.data.code === 200) {
          this.clueList = res.data.data.list;
          this.total = res.data.data.total;
          this.pageSize = res.data.data.pageSize;
        }
      })
    },
    /**
     * 加载用户下拉框选项
     */
    loadUserSelect(){
      //加载负责人
      doGet("api/loadUserSelect",{}).then(res =>{
        if (res.data.code === 200) {
          this.clueUserSelect = res.data.data;
        }else {
          messageTip("加载负责人下拉选项失败","error")
        }
      })
    },
    /**
     * 加载活动下拉框
     *
     */
    loadActivitySelect() {
      doGet("api/loadActivitySelect",{}).then(res =>{
        if (res.data.code === 200) {
          this.activitySelect = res.data.data;
        }else {
          messageTip("加载负责人下拉选项失败","error")
        }
      })
    },

    /**
     * 根据类型加载下拉框
     *
     */
    loadAppellationSelect(typeCode) {
      //2是称呼
      doGet("api/loadDicSelect",{
        select:typeCode
      }).then(res =>{
        if (res.data.code === 200) {
          if (typeCode === 'appellation'){
            this.appellationSelect = res.data.data;
          }

          if (typeCode === 'needLoan'){
            this.needLoadSelect = res.data.data;
          }

          if (typeCode === 'intentionState'){
            this.intentionStateSelect = res.data.data;
          }

          if (typeCode === 'clueState'){
            this.clueStateSelect = res.data.data;
          }

          if (typeCode === 'source'){
            this.sourceSelect = res.data.data;
          }



        }else {
          messageTip("加载失败","error")
        }
      })
    },
    /**
     * 加载产品列表
     *
     */
    loadProductSelect() {
      doGet("api/loadProductSelect",{}).then(res =>{
        if (res.data.code === 200) {
          this.productSelect = res.data.data
        }
      })
    },
    page(number) {
      this.getClueInfo(number)
    },
    details(id) {
      //跳转路由
      this.$router.push('/hello/clueDetails/' + id)
    },
    /**
     * 录入线索
     */
    addClue(){
      this.clueQuery = {};
      this.dialogFormVisible = true;
      this.loadLoginInfo()
      this.loadAllSelect()
    },
    loadAllSelect(){
      //加载下拉框
      this.loadUserSelect();
      this.loadActivitySelect();
      this.loadAppellationSelect('appellation');
      this.loadAppellationSelect('needLoan');
      this.loadAppellationSelect('intentionState');
      this.loadAppellationSelect('clueState');
      this.loadAppellationSelect('source');
      this.loadProductSelect();
    },
    /**
     * 加载当前登录人信息
     */
    loadLoginInfo() {
      doGet("api/loadLoginInfo",{}).then(res =>{
        if (res.data.code === 200) {
          this.clueQuery.ownerId = res.data.data.id;
        }
      })
    },
    submitClue() {
      //编辑和新增的公用
      this.$refs.dialogRef.validate( (valid) =>{
            if (valid) {
              let formdata = new FormData();
              for (let clueData in this.clueQuery) {
                formdata.append(clueData, this.clueQuery[clueData])
              }

              if(this.clueQuery.id > 0){
                doPut('api/editClue', this.clueQuery).then( res => {
                  if (res.data.code === 200) {
                    //提示信息
                    messageTip("编辑线索成功", "success")
                    //刷新页面
                    this.reload();
                  }else {
                    messageTip("添加线索失败！原因是：" + res.data.msg, "error")
                  }
                })
              }else {
                //发送请求
                doPost('api/addClue', formdata).then( res => {
                  if (res.data.code === 200) {
                    //提示信息
                    messageTip("添加线索成功", "success")
                    //刷新页面
                    this.reload();
                  }else {
                    messageTip("添加、线索失败！原因是：" + res.data.msg, "error")
                  }
                });

              }
            }
      })

    },
    /**
     * 编辑线索
     * @param clueId
     */
    editClue(clueId){
        //编辑，新增共用一个弹窗。
      this.dialogFormVisible = true;
      //获取线索信息
      this.clueDetail(clueId);
    },
    /**
     * 删除用户
     * @param userId
     */
    delClue(clueId) {
      confirmMessageTip('确认删除此用户吗？').then(() => {
        //删除用户
        doDelete("api/delClue/" + clueId,{}).then(res =>{
          if (res.data.code === 200) {
            messageTip("删除成功", "success")
            //刷新
            this.reload();
          }else {
            messageTip(res.data.msg,"error")
          }
        })
      }).catch(() => {
            messageTip("取消", "info")
          })
    },
    /**
     * 批量删除
     */
    batchDelClue() {
      if (this.clueIdArray.length === 0){
        messageTip("请选择需要删除的用户！", "warning")
      }else {

        //批量删除用户
        confirmMessageTip('您确定要删除当前选中用户吗？').then(() => {
          let ids = this.clueIdArray.join(",")
          doDelete("api/clueDelBatch",{ids:ids}).then(res =>{
            if (res.data.code === 200){
              messageTip("删除成功", "success")
              this.reload();
            }else {
              messageTip("删除失败，原因是：" + res.data.msg, "error")
              this.reload();
            }
          })
        }).catch(()=>{
          messageTip("取消","warning")
        })
      }
    },
    /**
     * 获取线索信息
     * @param id
     */
    clueDetail(id) {
      this.loadAllSelect();
      doGet("api/clueDetail/" + id, {}).then(res =>{
        if (res.data.code === 200) {
          this.clueQuery = res.data.data;
        }
      })
    },

  },
  mounted() {
    //分页 默认第一页
    this.getClueInfo(1);
  }
}
</script>


<style scoped>
.edit{
  margin-bottom: 15px;
}

.page{
  display: flex;
  justify-content: center;
}
.el-table{
  overflow: auto;
}
</style>